<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 微信相关接口处理
 */
class Controller_Pc_Api_V2_Wxclient extends Controller_Pc_Api_v2_Base
{
    private $_api;
    private $_conf = null;
    private $_mid = '';

    public function before()
    {
        parent::before();
        self::_conf();
        require_once BASEPATH.'plugins/api/vendor/api/weixin.class.php';

        $token = Common::remove_xss($this->request_data->token);
        $check_token = Model_Api_V2_Pub::token_decode($token);
        if($check_token['status'])
        {
            $this->_mid = $check_token['status']?$check_token['mid']:0;
        }
    }

    /**
     * 获取微信快速登录信息
     */
    public function action_login()
    {
        try {
            if(St_Functions::is_normal_app_install('weixinquicklogin'))
            {
                // 已登录状态
                if($this->_mid)
                {
                    // 检查是否绑定微信
                    $sql = "SELECT t.mid,m.mobile FROM sline_member_third t INNER JOIN sline_member m on(t.mid = m.mid) WHERE t.mid='{$this->_mid}' and t.wx_openid <> '' and m.mobile <> '' LIMIT 1" ;
                    $ar = DB::query(Database::SELECT, $sql)->execute()->current();
                    if(!empty($ar['mid']))
                    {
                        throw new Exception(__("已绑定微信且正常登录"));
                    }
                }

                if($this->_conf['appid'] && $this->_conf['appkey'])
                {
                    // 判断是否开启微信快速登录
                    $state  = 'wxclientlogin';
                    $author = new weixinPHP($this->_conf['appid'], $this->_conf['appkey'], $this->_conf['callback'], $state);
                    $url = $author->login_url();
                    $result = array(
                        'status'=> true,
                        'msg'=> '获取成功',
                        'data'=> array('url'=> $url)
                    );
                }
                else
                {
                    throw new Exception("微信快速登录参数配置有误");
                }
            }

        }
        catch (Exception $err)
        {
            $result = array('status' => false, 'msg' => $err->getMessage());
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //微信回调
    public function action_callback()
    {
        $user = array();
        $code = $this->request_data->code;
        $fxpcode = $this->request_data->fxpcode;
        $author = new weixinPHP($this->_conf['appid'], $this->_conf['appkey'], $this->_conf['callback'], time());
        try{

            $tokenarr = $author->access_token($code);
            if(!isset($tokenarr['openid'])||!isset($tokenarr['access_token'])){
                throw new Exception('获取Openid失败');
            }
            $token  = $tokenarr['access_token'];
            $openid = $tokenarr['openid'];
            $author = $author->get_user_info($openid, $token);

            if (isset($author['openid']))
            {
                $author['unionid'] = $author['unionid'] ? $author['unionid'] : $author['openid'];
                $user['openid'] = $author['unionid'];
                $user['unionid'] = $author['unionid'];
                $user['nickname'] = $author['nickname'];
                $user['litpic'] = $author['headimgurl'];
                $user['wx_openid'] = $author['openid'];
                $user['come_from'] = 'weixin';
                // 已登录状态
                if($this->_mid)
                {
                    $user['mid'] = $this->_mid;
                    Model_Api_V2_Member_Login::third_login_bind($user);
                    // 获取用户登录信息
                    $member = Model_Member::get_member_byid($this->_mid);
                    $data = Model_Api_V2_Member_Login::login_init($member);
                    $result = array(
                        'status' => true,
                        'msg' => '登录成功',
                        'data'=> $data
                    );
                    $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
                }

                // 未登录状态
                $rs = Db::query(Database::SELECT,'(select * from `sline_member_third` where wx_openid="' . $author['openid'] . '") union (select * from `sline_member_third` where openid="' . $author['unionid'] . '")')->execute()->current();
                if (!empty($rs))
                {
                    if ($rs['openid'] != $author['unionid'])
                    {
                        //更改openId
                        DB::update('member_third')->set(array('openid' => $author['unionid']))->where('id', '=', $rs['id'])->execute();
                        //整理多余用户
                        $richUser = DB::select()->from('member_third')->where('openid', '=', $author['unionid'])->and_where('id', '<>', $rs['id'])->execute()->current();
                        if ($richUser)
                        {
                            DB::delete('member_third')->where('id', '=', $richUser['id'])->execute();
                            DB::delete('member')->where('mid', '=',  $richUser['mid'])->execute();
                            DB::update('member_order')->set(array('memberid' => $rs['mid']))->where('memberid', '=', $richUser['mid'])->execute();
                        }
                    }
                    if (!empty($rs['nickname']))
                    {
                        unset($user['nickname']);
                    }
                    //这里补充记录微信公众号的用户openid用于微信公众号的相关应用操作.
                    DB::update('member_third')->set(array('wx_openid' => $user['wx_openid']))->where('mid', '=', $rs['mid'])->execute();
                    Model_Api_V2_Member_Login::write_login_info($rs);
                }

                $cfg_third_login_bind = Model_Sysconfig::get_configs(0,'cfg_third_login_bind',true);
                $res = Model_Api_V2_Member_Login::third_bind(array('third'=>$user));
                // 新增用户
                if($res['bool'])
                {
                    $rs = Db::query(Database::SELECT,'(select * from `sline_member_third` where wx_openid="' . $author['openid'] . '") union (select * from `sline_member_third` where openid="' . $author['unionid'] . '")')->execute()->current();
                    //检测用户是否存在
                    $member = Model_Member::get_member_byid($rs['mid']);
                    //用户注册后信息处理
                    Model_Api_V2_Member_Login::write_login_info($rs);
                    // 检查是否安装分销商应用
                    if(St_Functions::is_normal_app_install('mobiledistribution'))
                    {
                        // 检查是否是分销商
                        $is_fenxiao = DB::select('fxcode','status')->from('fenxiao')->where('memberid','=',$rs['mid'])->execute()->current();
                        if(!$is_fenxiao && !empty($fxpcode))
                        { // 不是分销商且分销商fxcode不为空
                            Model_Fenxiao::invite($rs['mid'], $fxpcode);
                        }
                    }
                    //获取登录配置
                    $data = Model_Api_V2_Member_Login::login_init($member);
                    $data['cfg_third_login_bind'] = $cfg_third_login_bind; // 登陆后绑定的方式
                    $result = array(
                        'status' => true,
                        'msg' => '登录成功',
                        'data'=> $data
                    );
                }
                else
                {
                    $result = array(
                        'status' => false,
                        'msg' => '用户注册失败',
                        'data'=> array(
                            'errCode'=> 2,
                            'author'=> $author
                        )
                    );
                }
            }
            else
            {
                $result = array(
                    'status' => false,
                    'msg' => '获取用户信息失败',
                    'data'=> array(
                        'errCode'=> 1,
                        'author'=> $author
                    )
                );
            }
        }catch (Exception $err){
            $result = array(
                'status' => false,
                'msg' => $err->getMessage(),
                'data'=> $author
            );
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    /**
     * 配置第三方登录信息
     */
    private function _conf()
    {
        $arr = DB::select()->from('sysconfig')->where("varname in('cfg_wx_client_appkey','cfg_wx_client_appsecret')")->execute()->as_array();
        $info = array(
            "callback" => Common::get_main_host() . "/h5/"
        );
        foreach ($arr as $v) {
            if ($v['varname'] == 'cfg_wx_client_appkey') {
                $info['appid'] = $v['value'];
            }
            if ($v['varname'] == 'cfg_wx_client_appsecret') {
                $info['appkey'] = $v['value'];
            }
        }
        $config = Model_Sysconfig::get_configs(0, array('cfg_global_wx_appkey', 'cfg_global_wx_appsecret'));
        $info['appid'] = $config['cfg_global_wx_appkey'] ? $config['cfg_global_wx_appkey'] : $info['appid'];
        $info['appkey'] = $config['cfg_global_wx_appsecret'] ? $config['cfg_global_wx_appsecret'] : $info['appkey'];
        $this->_conf = $info;
    }
}